/**
 * Created by zxr on 16/11/17.
 */
function divEscapedContentElement(message){
	return $('<div></div>').text(message);
}
function divSystemContentElement(message,cla){
	return $('<div></div>').addClass(cla).html('<i>' + message + '</i>');
}

function processUserInput(chatApp){
	var message = $('#send-message').val();
	var systemMessage;
	if (message.charAt(0) == '/'){
		systemMessage = chatApp.processCommand(message);
	}
	if (systemMessage){
		$('#messages').append(divSystemContentElement(message))
	} else {
		var room = $('#room').text();
		var height = $('#messages').prop('scrollHeight');
		chatApp.sendMessage(room, message);
		$('#messages').append(divEscapedContentElement(message));
		$('#messages').scrollTop(height);
	}
	$('#send-message').val('');
}

// 辅助函数完毕
/*
* 客户端程序初始化逻辑
*
* */
var socket = io.connect();
$(document).ready(function(){
	var chatApp = new Chat(socket);
	socket.on('nameResult',function(result){
		var message = undefined;
		if (result.success){
			message = 'You are now known as ' + result.name + '.';
		} else{
			message = result.message;
		}
		$('#messages').append(divSystemContentElement(message,'changename'));
	});
	// 用户加入
	socket.on('joinResult', function(result){
		$('#room').text(result.room);
		$('#messages').append(divSystemContentElement(result.message)).find('i').addClass('join');
	});

	socket.on('rooms', function(rooms){
		$('#room-list').empty();
		for (var room in rooms){
			room = room.substring(1, rooms.length);
			if (room != ''){
				$('#room-list').append(divEscapedContentElement(room));
			}
		};
		$('room-list div').on('click', function() {
			chatApp.processCommand('/join' + $(this).text());
			$('#send-message').focus();
		})
	});
	socket.on('message',function(result){
		console.warn(result)
		$('#messages').append(divSystemContentElement(result.text,'warn'));
	});
	socket.on('broadcast-message',function(result){
		console.warn(result)
		$('#messages').append(divEscapedContentElement(result.text));
	});
	socket.on('leave',function(result){
		console.warn(result)
		$('#messages').append(divSystemContentElement(result.text,'warn'));
	});
	socket.on('time',function(time){
		$('#time').text(time);
	});
// 定期请求可用房间列表
	setInterval(function() {
		socket.emit('rooms');
	},1000);
	$('#send-message').focus();
	$('#send-form').submit(function() {
		processUserInput(chatApp);
		return false;
	})
});